package com.interceptor;

import java.lang.reflect.Parameter;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;



/**
 * Created by chenboge on 2017/5/7.
 * <p>
 * Email:baigegechen@gmail.com
 * <p>
 * description:
 */

/**
 * @param <T>
 * @Intercepts 说明是一个拦截器
 * @Signature 拦截器的签名 type 拦截的类型 四大对象之一(
 *            Executor,ResultSetHandler,ParameterHandler,StatementHandler)
 *            method 拦截的方法 args 参数
 */

public class ParamNullInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o)
			throws Exception {
		HandlerMethod handlerMethod = (HandlerMethod) o;
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
		System.out.println(handlerMethod.getMethod().getName() + "--------");
		Parameter[] parameters = handlerMethod.getMethod().getParameters();

		//System.out.println(parameters[0].getParameterizedType().getTypeName());

		
        Object obj = getTrueClassObject(parameters[0].getParameterizedType());
		//ProcessNull.process(obj);
		return true;
	}

	public Class getTrueClassObject(Type type) {
		Class clazz = null;
        //2.得到运行类的父类的参数化类型
        //把ptype转换成Type的子接口类型
        if (type instanceof ParameterizedType) {
             
            ParameterizedType ptype=(ParameterizedType) type;
            //3.得到实际类型参数
            Type[] types = ptype.getActualTypeArguments();
            //4.把types变成其实现类Class
            Class classImpl =(Class) types[0];
            clazz=classImpl;
        }
        return clazz;
	}

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

}
